package com.example.aimultimodel.tools;

import org.springframework.ai.tool.annotation.Tool;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 数学计算工具类
 *
 * @author 18747
 */
public class MathCalculatorTool {

    /**
     * 执行基本数学运算
     *
     * @param expression 数学表达式,支持 +、-、*、/、%、^(幂运算)
     * @return 计算结果
     */
    @Tool(description = "执行数学计算,支持基本运算符: +、-、*、/、%(取模)、^(幂运算)。例如: '10 + 5 * 2'")
    public String calculate(String expression) {
        try {
            expression = expression.replaceAll("\\s+", "");
            double result = evaluateExpression(expression);
            return String.format("计算结果: %s = %.4f", expression, result);
        } catch (Exception e) {
            return "计算错误: " + e.getMessage();
        }
    }

    /**
     * 计算圆的面积
     *
     * @param radius 半径
     * @return 圆的面积
     */
    @Tool(description = "计算圆的面积,参数为半径")
    public String calculateCircleArea(double radius) {
        if (radius <= 0) {
            return "错误: 半径必须大于0";
        }
        double area = Math.PI * radius * radius;
        return String.format("半径为 %.2f 的圆的面积为: %.4f", radius, area);
    }

    /**
     * 计算矩形面积
     *
     * @param length 长度
     * @param width  宽度
     * @return 矩形面积
     */
    @Tool(description = "计算矩形面积,参数1为长度,参数2为宽度")
    public String calculateRectangleArea(double length, double width) {
        if (length <= 0 || width <= 0) {
            return "错误: 长度和宽度必须大于0";
        }
        double area = length * width;
        return String.format("长 %.2f、宽 %.2f 的矩形面积为: %.4f", length, width, area);
    }

    /**
     * 计算平方根
     *
     * @param number 数字
     * @return 平方根
     */
    @Tool(description = "计算数字的平方根")
    public String calculateSquareRoot(double number) {
        if (number < 0) {
            return "错误: 不能计算负数的平方根";
        }
        double result = Math.sqrt(number);
        return String.format("%.4f 的平方根为: %.4f", number, result);
    }

    /**
     * 计算百分比
     *
     * @param part  部分值
     * @param total 总值
     * @return 百分比
     */
    @Tool(description = "计算百分比,参数1为部分值,参数2为总值")
    public String calculatePercentage(double part, double total) {
        if (total == 0) {
            return "错误: 总值不能为0";
        }
        double percentage = (part / total) * 100;
        return String.format("%.2f 占 %.2f 的百分比为: %.2f%%", part, total, percentage);
    }

    /**
     * 计算复利
     *
     * @param principal 本金
     * @param rate      年利率(百分比)
     * @param years     年数
     * @return 复利结果
     */
    @Tool(description = "计算复利,参数1为本金,参数2为年利率(百分比),参数3为年数")
    public String calculateCompoundInterest(double principal, double rate, int years) {
        if (principal <= 0 || rate <= 0 || years <= 0) {
            return "错误: 参数必须大于0";
        }
        double amount = principal * Math.pow(1 + rate / 100, years);
        double interest = amount - principal;
        return String.format(
                "本金: %.2f, 年利率: %.2f%%, 年数: %d\n最终金额: %.2f\n利息: %.2f",
                principal, rate, years, amount, interest
        );
    }

    /**
     * 简单的表达式求值(支持+-* /和括号)
     */
    private double evaluateExpression(String expr) {
        return new Object() {
            int pos = -1, ch;

            void nextChar() {
                ch = (++pos < expr.length()) ? expr.charAt(pos) : -1;
            }

            boolean eat(int charToEat) {
                while (ch == ' ') nextChar();
                if (ch == charToEat) {
                    nextChar();
                    return true;
                }
                return false;
            }

            double parse() {
                nextChar();
                double x = parseExpression();
                if (pos < expr.length()) throw new RuntimeException("意外字符: " + (char) ch);
                return x;
            }

            double parseExpression() {
                double x = parseTerm();
                for (; ; ) {
                    if (eat('+')) x += parseTerm();
                    else if (eat('-')) x -= parseTerm();
                    else return x;
                }
            }

            double parseTerm() {
                double x = parseFactor();
                for (; ; ) {
                    if (eat('*')) x *= parseFactor();
                    else if (eat('/')) x /= parseFactor();
                    else if (eat('%')) x %= parseFactor();
                    else return x;
                }
            }

            double parseFactor() {
                if (eat('+')) return +parseFactor();
                if (eat('-')) return -parseFactor();

                double x;
                int startPos = this.pos;
                if (eat('(')) {
                    x = parseExpression();
                    if (!eat(')')) throw new RuntimeException("缺少')'");
                } else if ((ch >= '0' && ch <= '9') || ch == '.') {
                    while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
                    x = Double.parseDouble(expr.substring(startPos, this.pos));
                } else {
                    throw new RuntimeException("意外字符: " + (char) ch);
                }

                if (eat('^')) x = Math.pow(x, parseFactor());

                return x;
            }
        }.parse();
    }
}
